package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.constants.Constants;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.enums.AppUpdateFileTypeEnum;
import com.easychat.entity.po.AppUpdate;
import com.easychat.entity.query.AppUpdateQuery;
import com.easychat.entity.vo.AppUpdateVO;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.StringTools;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@RestController("updateController")
@RequestMapping("/update")
public class UpdateController extends ABaseController{

    @Resource
    private AppUpdateService appUpdateService;
    @Resource
    private AppConfig appConfig;

    /**
     * 版本检测
     * @param appVersion 客户端版本
     * @param uid 用户id
     * @return
     */
    @RequestMapping("/checkVersion")
    @GlobalInterceptor
    public ResponseVO checkVersion(String appVersion, String uid) {
        if (StringTools.isEmpty(appVersion)) {
            return getSuccessResponseVO(null);
        }
        AppUpdate latestUpdate = appUpdateService.getLatestUpdate(appVersion, uid);
        if (latestUpdate == null) {
            return getSuccessResponseVO(null);
        }
        AppUpdateVO appUpdateVO = new AppUpdateVO();
        BeanUtils.copyProperties(latestUpdate, appUpdateVO);
        if (AppUpdateFileTypeEnum.LOCAL.getType().equals(latestUpdate.getFileType())) {
            //如果是外链，则无法直接获取文件大小
            //只有本地可以
            File file = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER + latestUpdate.getId() + Constants.APP_UPDATE_EXTENSION);
            appUpdateVO.setSize(file.length());
        } else {
            appUpdateVO.setSize(0L);
        }
        appUpdateVO.setUpdateList(Arrays.asList(latestUpdate.getUpdateDesc()));
        appUpdateVO.setFileName(Constants.APP_NAME + latestUpdate.getVersion() + Constants.APP_UPDATE_EXTENSION);
        return getSuccessResponseVO(appUpdateVO);
    }


}
